﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using WPadkCore;
using System.Text;
using Microsoft.Phone.Shell;

namespace WPadkDemo
{
    public partial class MainPage : PhoneApplicationPage
    {
        WPadkPoxy poxy;
        WPadkClient adkClient;

        // Constructor
        public MainPage()
        {
            InitializeComponent();
            Loaded += new RoutedEventHandler(MainPage_Loaded);
            bt1.Click += new RoutedEventHandler(bt1_Click);
            bt2.Click += new RoutedEventHandler(bt2_Click);
            ts_io2.Checked += new EventHandler<RoutedEventArgs>(ts_io2_Checked);
            ts_io3.Checked += new EventHandler<RoutedEventArgs>(ts_io2_Checked);
            ts_io4.Checked += new EventHandler<RoutedEventArgs>(ts_io2_Checked);
            ts_io5.Checked += new EventHandler<RoutedEventArgs>(ts_io2_Checked);
            ts_io6.Checked += new EventHandler<RoutedEventArgs>(ts_io2_Checked);
            ts_io7.Checked += new EventHandler<RoutedEventArgs>(ts_io2_Checked);
            ts_io8.Checked += new EventHandler<RoutedEventArgs>(ts_io2_Checked);
            ts_io9.Checked += new EventHandler<RoutedEventArgs>(ts_io2_Checked);

            ts_io2.Unchecked += new EventHandler<RoutedEventArgs>(ts_io2_Unchecked);
            ts_io3.Unchecked += new EventHandler<RoutedEventArgs>(ts_io2_Unchecked);
            ts_io4.Unchecked += new EventHandler<RoutedEventArgs>(ts_io2_Unchecked);
            ts_io5.Unchecked += new EventHandler<RoutedEventArgs>(ts_io2_Unchecked);
            ts_io6.Unchecked += new EventHandler<RoutedEventArgs>(ts_io2_Unchecked);
            ts_io7.Unchecked += new EventHandler<RoutedEventArgs>(ts_io2_Unchecked);
            ts_io8.Unchecked += new EventHandler<RoutedEventArgs>(ts_io2_Unchecked);
            ts_io9.Unchecked += new EventHandler<RoutedEventArgs>(ts_io2_Unchecked);

            ts_io2.Click += new EventHandler<RoutedEventArgs>(ts_io2_Click);
            ts_io3.Click += new EventHandler<RoutedEventArgs>(ts_io2_Click);
            ts_io4.Click += new EventHandler<RoutedEventArgs>(ts_io2_Click);
            ts_io5.Click += new EventHandler<RoutedEventArgs>(ts_io2_Click);
            ts_io6.Click += new EventHandler<RoutedEventArgs>(ts_io2_Click);
            ts_io7.Click += new EventHandler<RoutedEventArgs>(ts_io2_Click);
            ts_io8.Click += new EventHandler<RoutedEventArgs>(ts_io2_Click);
            ts_io9.Click += new EventHandler<RoutedEventArgs>(ts_io2_Click);

            bt_取数字端口.Click += new RoutedEventHandler(bt_取数字端口_Click);
            bt_取数字端口1.Click +=new RoutedEventHandler(bt_取数字端口_Click);

            ts_hl2.Click += new EventHandler<RoutedEventArgs>(ts_hl2_Click);
            ts_hl3.Click += new EventHandler<RoutedEventArgs>(ts_hl2_Click);
            ts_hl4.Click += new EventHandler<RoutedEventArgs>(ts_hl2_Click);
            ts_hl5.Click += new EventHandler<RoutedEventArgs>(ts_hl2_Click);
            ts_hl6.Click += new EventHandler<RoutedEventArgs>(ts_hl2_Click);
            ts_hl7.Click += new EventHandler<RoutedEventArgs>(ts_hl2_Click);
            ts_hl8.Click += new EventHandler<RoutedEventArgs>(ts_hl2_Click);
            ts_hl9.Click += new EventHandler<RoutedEventArgs>(ts_hl2_Click);

            sd_p3.ValueChanged += new RoutedPropertyChangedEventHandler<double>(sd_p3_ValueChanged);
            sd_p5.ValueChanged += new RoutedPropertyChangedEventHandler<double>(sd_p3_ValueChanged);
            sd_p6.ValueChanged += new RoutedPropertyChangedEventHandler<double>(sd_p3_ValueChanged);
            sd_p9.ValueChanged += new RoutedPropertyChangedEventHandler<double>(sd_p3_ValueChanged);

            bt_IrLrean.Click += new RoutedEventHandler(bt_IrLrean_Click);
            bt_IrSend.Click += new RoutedEventHandler(bt_IrSend_Click);

            bt_setupServo.Click += new RoutedEventHandler(bt_setupServo_Click);
            bt_ServoSend.Click += new RoutedEventHandler(bt_ServoSend_Click);

            bt_串口启用.Click += new RoutedEventHandler(bt_串口启用_Click);
            bt_串口发送.Click += new RoutedEventHandler(bt_串口发送_Click);
            bt_串口接收.Click += new RoutedEventHandler(bt_串口接收_Click);
            bt_串口取消接收.Click += new RoutedEventHandler(bt_串口取消接收_Click);
            bt_重置.Click += new RoutedEventHandler(bt_重置_Click);
        }

        void bt_重置_Click(object sender, RoutedEventArgs e)
        {
            if (isConnected)
            {
                reset();
            }
        }

        void bt_串口取消接收_Click(object sender, RoutedEventArgs e)
        {
            if (isConnected)
            {
                poxy.ToADK(adkClient.SetReadSerial(SerialReadMode.NoRead));
            }
        }

        void bt_串口接收_Click(object sender, RoutedEventArgs e)
        {
            if (isConnected)
            {
                poxy.ToADK(adkClient.SetReadSerial(SerialReadMode.Read));
            }
        }

        void bt_串口发送_Click(object sender, RoutedEventArgs e)
        {
            if (tb_串口数据.Text != string.Empty)
            {
                if (isConnected)
                {
                    poxy.ToADK(adkClient.SendSerial(Encoding.UTF8.GetBytes(tb_串口数据.Text)));
                }
            }
        }

        void bt_串口启用_Click(object sender, RoutedEventArgs e)
        {
            if (checkInt(tb_比特率.Text))
            {
                if (isConnected)
                {
                    poxy.ToADK(adkClient.StartSerial(int.Parse(tb_比特率.Text)));
                }
            }
        }

        bool checkInt(string str)
        {
            try
            {
                int d = int.Parse(str);
                return true;
            }
            catch
            {
                return false;
            }
        }

        void bt_ServoSend_Click(object sender, RoutedEventArgs e)
        {
            if (checkInt(tb_ServoPin.Text) && checkInt(tb_ServoPot.Text))
            {
                if (isConnected)
                {
                    poxy.ToADK(adkClient.SetServor(int.Parse(tb_ServoPin.Text), (byte)int.Parse(tb_ServoPot.Text)));
                }
            }
        }

        void bt_setupServo_Click(object sender, RoutedEventArgs e)
        {
            if (checkInt(tb_ServoPin.Text))
            {
                if (isConnected)
                {
                    poxy.ToADK(adkClient.SetPinMode(int.Parse(tb_ServoPin.Text), pMode.OUTPUT));
                }
            }
        }

        void bt_IrSend_Click(object sender, RoutedEventArgs e)
        {
            if (tb_IrData.Text != string.Empty)
            {
                if (isConnected)
                {
                    poxy.ToADK(adkClient.SendIRRemote(tb_IrData.Text));
                }
            }
        }

        void bt_IrLrean_Click(object sender, RoutedEventArgs e)
        {
            if (checkInt(tb_IrLreanPin.Text))
            {
                if (isConnected)
                {
                    poxy.ToADK(adkClient.runIRReader((byte)int.Parse(tb_IrLreanPin.Text)));
                }
            }
        }

        void sd_p3_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            var sd = sender as Slider;
            var pin = int.Parse(sd.Name.Substring(4, 1));
            if (isConnected)
            {
                poxy.ToADK(adkClient.SetPWM(pin, (byte)sd.Value));
            }
        }

        void ts_hl2_Click(object sender, RoutedEventArgs e)
        {
            var ts = sender as ToggleSwitch;
            var pin = int.Parse(ts.Header.ToString().Substring(1, 1));
            if (isConnected)
            {
                poxy.ToADK(adkClient.SetDigital(pin, ts.IsChecked.Value ? dMode.HIGH : dMode.LOW));
            }
        }

        void bt_取数字端口_Click(object sender, RoutedEventArgs e)
        {
            if (isConnected)
            {
                GetAllAD();
            }
        }

        void ts_io2_Click(object sender, RoutedEventArgs e)
        {
            var ts = sender as ToggleSwitch;
            var pin = int.Parse(ts.Header.ToString().Substring(1, 1));
            if (isConnected)
            {
                poxy.ToADK(adkClient.SetPinMode(pin, ts.Content.ToString() == "IN" ? pMode.INPUT : pMode.OUTPUT));
            }
        }

        void ts_io2_Unchecked(object sender, RoutedEventArgs e)
        {
            var ts = sender as ToggleSwitch;
            ts.Content = "IN";
        }

        void ts_io2_Checked(object sender, RoutedEventArgs e)
        {
            var ts = sender as ToggleSwitch;
            ts.Content = "OUT";
        }

        void bt2_Click(object sender, RoutedEventArgs e)
        {
            GetDHT1x();
        }

        void bt1_Click(object sender, RoutedEventArgs e)
        {
            if (poxy != null)
            {
                adkClient = new WPadkClient(tb_pwd.Text);
                poxy.Connect(tb_ip.Text, 80, 1024);
            }
        }

        void reset()
        {
            //重置，硬件DYid为wpadk
            poxy.ToADK(adkClient.resetAll(tb_dyid.Text));
        }

        void SetRePwd()
        {
            //123456为新密码
            poxy.ToADK(adkClient.setPwd("123456"));
        }

        void IrSend()
        {
            poxy.ToADK(adkClient.SendIRRemote(@"9000,4500,600,550,600,500,600,500,600,600,550,500,650,
550,550,550,600,500,600,1650,600,1650,600,1650,600,1650,600,1650,550,1700,650,1600,650,
1600,600,1650,650,500,600,550,550,550,600,500,600,550,600,500,650,500,550,600,600,1650,500,
1700,650,1650,600,1650,500,1750,600,1650,600,1650,500"));
        }

        void RunIRReader()
        {
            poxy.ToADK(adkClient.runIRReader(6));
        }

        void GetAllAD()
        {
            poxy.ToADK(adkClient.GetAllDigitalAndAnalog());
        }

        void GetAnalog()
        {
            poxy.ToADK(adkClient.GetAnalog(5));
        }

        void GetDigital()
        {
            poxy.ToADK(adkClient.GetDigital(3));
        }

        void GetDHT1x()
        {
            //默认A0接口
            poxy.ToADK(adkClient.GetDHT1x());
        }

        void SetReadSerial()
        {
            poxy.ToADK(adkClient.SetReadSerial(SerialReadMode.Read));
        }

        void setDigital()
        {
            poxy.ToADK(adkClient.SetPinMode(3, pMode.OUTPUT));
            poxy.ToADK(adkClient.SetDigital(3, dMode.HIGH));
        }

        void setPwm()
        {
            poxy.ToADK(adkClient.SetPWM(3, 255));
        }

        void SendSerial()
        {
            poxy.ToADK(adkClient.SendSerial(Encoding.UTF8.GetBytes("wpadk is good pd ")));
        }

        void startSerial()
        {
            var result = poxy.ToADK(adkClient.StartSerial(19200));
            listBox1.Items.Insert(0, result);
        }

        void setRelay()
        {
            poxy.ToADK(adkClient.SetPinMode(8, pMode.OUTPUT));
            poxy.ToADK(adkClient.SetDigital(9, dMode.HIGH));
        }

        void setServo()
        {
            //poxy.ToADK(adkClient.SetPinMode(8, pMode.OUTPUT));
            //poxy.ToADK(adkClient.SetServor(170));
        }

        void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            PhoneApplicationService.Current.ApplicationIdleDetectionMode = IdleDetectionMode.Disabled;
            //实例化DYCom客户端实例,服务端地址，端口号，缓冲区大小
            poxy = new WPadkPoxy();
            //连接事件注册处理函数
            poxy.onConnet = new OnConnet(onConnect);
            //消息到来事件注册处理函数
            poxy.onData = new OnData(onData);
            //断开连接事件注册处理函数
            poxy.onDisconnet = new OnDisConnet(ondisConnect);
        }

        bool isConnected = false;
        void onConnect(bool result)
        {
            isConnected = result;
            //显示于listbox1
            //listBox1.Items.Insert(0, result.ToString());
            if (result)
            {
                listBox1.Items.Insert(0, "已连接");
            }
            else
            {
                listBox1.Items.Insert(0, "未连接");
            }
        }

        //数据消息到来件事
        void onData(byte[] data)
        {
            WPadkDecoder smartDecoder = new WPadkDecoder();
            smartDecoder.initData(data);
            operations? opera = smartDecoder.getOperation();
            if (opera.HasValue)
            {
                object dt = smartDecoder.decode(opera.Value);
                if (opera == operations.BeginSerial || opera == operations.ResetAll || opera == operations.SetPwd || opera == operations.SerialSend
                || opera == operations.PinMode || opera == operations.SetDigital || opera == operations.SetPWM || opera == operations.SetServo
                || opera == operations.GetDigital || opera == operations.GetAnalog)
                {
                    listBox1.Items.Insert(0, dt.ToString());
                }
                else if (opera == operations.GetDHT1x)
                {
                    if (dt.ToString().Contains("NotFind"))
                    {
                        listBox1.Items.Insert(0, dt);
                        return;
                    }
                    dht1xData dht = dt as dht1xData;
                    //listBox1.Items.Insert(0, "当前温度:" + dht.Temperature.ToString("n2") + "C 相对湿度:" + dht.Humidity.ToString("n2") + "%");
                    tbk_湿度.Text = dht.Humidity.ToString("n2") + "%";
                    tbk_温度.Text = dht.Temperature.ToString("n2") + "C";
                    any_temp.Begin();
                }
                else if (opera == operations.GetAllDigitalAndAnalog)
                {
                    IOs io = adkClient.Mapper.ToObject<IOs>(dt.ToString());
                    ts_hl2.IsChecked = io.digitals[0] == 0 ? false : true;
                    ts_hl3.IsChecked = io.digitals[1] == 0 ? false : true;
                    ts_hl4.IsChecked = io.digitals[2] == 0 ? false : true;
                    ts_hl5.IsChecked = io.digitals[3] == 0 ? false : true;
                    ts_hl6.IsChecked = io.digitals[4] == 0 ? false : true;
                    ts_hl7.IsChecked = io.digitals[5] == 0 ? false : true;
                    ts_hl8.IsChecked = io.digitals[6] == 0 ? false : true;
                    ts_hl9.IsChecked = io.digitals[7] == 0 ? false : true;
                    tbk_a1.Text = io.analogs[0].ToString();
                    tbk_a2.Text = io.analogs[1].ToString();
                    tbk_a3.Text = io.analogs[2].ToString();
                    tbk_a4.Text = io.analogs[3].ToString();
                    tbk_a5.Text = io.analogs[4].ToString();
                    tbk_a6.Text = io.analogs[5].ToString();
                    tbk_a7.Text = io.analogs[6].ToString();
                    listBox1.Items.Insert(0, dt.ToString());
                }
                else if (opera == operations.IRReadOnData)
                {
                    tb_IrData.Text = dt.ToString();
                    tbk_IrState.Text = "学习完成...";
                }
                else if (opera == operations.SetReSerial)
                {
                    listBox1.Items.Insert(0, dt.ToString());
                    if (dt.ToString().Contains("NoRead"))
                    {
                        tbk_串口提示.Text = "串口已停止接收状态....";
                    }
                    else
                    {
                        tbk_串口提示.Text = "串口启用接收状态....";
                    }
                }
                else if (opera == operations.SerialOnData)
                {
                    tb_串口接收数据.Text += dt.ToString();
                }
                else if (opera == operations.runIRReader)
                {
                    listBox1.Items.Insert(0, dt.ToString());
                    tbk_IrState.Text = "学习模式中..";
                }
                else if (opera == operations.SendIRRemote)
                {
                    listBox1.Items.Insert(0, dt.ToString());
                    tbk_IrState.Text = "发射完成...";
                }
            }
        }

        //用户断开事件
        void ondisConnect(string message)
        {
            //显示断开消息到UI
            listBox1.Items.Insert(0, message);
        }

    }
}